<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue";

const props = defineProps({
  /* 编辑器的内容 */
  content: {
    type: String,
    default: "",
  },
  /* 只读 */
  readonly: {
    type: Boolean,
    default: false,
  },
  // 上传文件大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  /* 高度 */
  height: {
    type: Number as any,
    default: 350,
  },
  /* 宽度 */
  width: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["update:content"]);

const styles = computed(() => {
  let style: any = {};
  // if (props.minHeight) {
  //   style.minHeight = `${props.minHeight}px`
  // }
  if (props.width) {
    style.width = `${props.width}`;
  }
  // if (props.height) {
  //   style.height = `${props.height}`;
  // }
  return style;
});

const curContent = ref<string>("");

watch(
  () => props.content,
  (val) => {
    if (val !== curContent.value) {
      curContent.value = val ? val : "";
    }
  },
  { immediate: true }
);

watch(
  () => curContent.value,
  (val) => {
    emit("update:content", val);
  },
  { immediate: true }
);

const editorConfig = {
  // 后端服务地址，后端处理参考
  // https://open-doc.modstart.com/ueditor-plus/backend.html

  // 仅保留表格功能
  toolbars: [
    [
      "table", // 表格
      "fontfamily", // 字体
      "fontsize", // 字号
      "forecolor", // 文字颜色
      // "backcolor",   // 背景色
      "bold", // 粗体
      "italic", // 斜体（斜杠效果）
      "underline", // 下划线
      "strikethrough", // 删除线
      "print", // 打印

      "inserttable", // 插入表格
      "deletetable", // 删除表格
      "insertrow", // 下方插入行
      "insertrownext", // 上方插入行
      "deleterow", // 删除行
      "insertcol", // 左侧插入列
      "insertcolnext", // 右侧插入列
      "deletecol", // 删除列
      "mergecells", // 合并单元格
      "splittocells", // 拆分单元格
    ],
  ],

  // // 禁用其他功能
  // enableContextMenu: false,
  // elementPathEnabled: false,
  // wordCount: false,

  serverUrl: "/ueditor.json",
  UEDITOR_HOME_URL: "/static/UEditorPlus/",
  UEDITOR_CORS_URL: "/static/UEditorPlus/",
  initialFrameHeight: props.height,
  autoHeightEnabled: false,
  readonly: props.readonly,
  imageConfig: {
    // 禁止本地上传
    disableUpload: false,
    // 禁止在线管理
    disableOnline: true,
  },
  videoConfig: {
    // 禁止本地上传,
    disableUpload: true,
  },
  toolbarCallback: function (cmd, editor) {
    switch (cmd) {
      case "simpleupload":
        // editor.execCommand('insertHtml', '<p><img src="xxxxx" /></p>');
        console.log("toolbarCallback", cmd, editor);
        return true;
      case "insertimage":
        // editor.execCommand('insertHtml', '<p><img src="xxxxx" /></p>');
        console.log("toolbarCallback", cmd, editor);
        return true;
      case "insertvideo":
        // editor.execCommand('insertHtml', '<p><img src="xxxxx" /></p>');
        console.log("toolbarCallback", cmd, editor);
        return true;
    }
  },
};

const editorInstance = ref<any>();

// 获取原始内容方法
const getRawContent = () => {
  console.log(editorInstance.value);
  return editorInstance.value?.editor?.getContent() || "";
};

// 获取纯文本内容方法
const getPlainText = () => {
  return editorInstance.value?.editor?.getContentTxt() || "";
};

// 获取过滤后的安全内容
const getFilteredContent = () => {
  const rawHtml = getRawContent();
  return filterTableContent(rawHtml);
};

// 表格内容过滤函数
const filterTableContent = (html: string) => {
  // 使用白名单过滤
  const allowedTags = ["table", "tbody", "tr", "td", "th", "caption"];
  const allowedAttrs = ["colspan", "rowspan", "border"];

  const doc = new DOMParser().parseFromString(html, "text/html");

  // 移除非表格元素
  doc.body.querySelectorAll("*").forEach((element) => {
    const tagName = element.tagName.toLowerCase();

    if (!allowedTags.includes(tagName)) {
      element.remove();
      return;
    }

    // 清理不允许的属性
    Array.from(element.attributes).forEach((attr) => {
      if (!allowedAttrs.includes(attr.name.toLowerCase())) {
        element.removeAttribute(attr.name);
      }
    });
  });

  return doc.body.innerHTML;
};

// 按钮点击处理
// const getContent = () => {
//   nextTick(() => {
//     console.log("HTML内容:", getFilteredContent());
//     console.log("纯文本内容:", getPlainText());

//     // 如果需要向外传递
//     emit("update:content", getFilteredContent());
//   });
// };

// 获取编辑器实例
const handleEditorReady = (instance) => {
  // console.log(instance, "instance");
  // console.log(instance.getUETable());
  // console.log(instance.getUETable());
  // console.log(instance.getContent());
  editorInstance.value = instance; // 关键：获取底层实例
  // console.log("编辑器已初始化");
};

// 获取内容的方法
const getContent = () => {
  // console.log(editorInstance.value);
  // console.log(editorInstance.value);
  if (!editorInstance.value) {
    return;
  }
  const htmlContent = editorInstance.value.getContent();
  const plainText = editorInstance.value.getContentTxt();
  console.log("HTML 内容:", htmlContent);
  console.log("纯文本:", plainText);
};

// onMounted(() => {
//   console.log(editorInstance.value);
// });

/* 方法暴露 */
defineExpose({ editorInstance })
</script>

<template>
  <div class="editor-u w-full">
    <vue-ueditor-wrap
      v-model="curContent"
      editor-id="editor"
      :config="editorConfig"
      :editorDependencies="['ueditor.config.js', 'ueditor.all.js']"
      :style="styles"
      @ready="handleEditorReady"
    />

    <!-- <a-button @click="getContent">获取内容</a-button> -->
  </div>
</template>

<style scoped lang="less">
.editor-u {
}

</style>
